#include "files.h"

MYFILE* mfopen(const char* filename, const char* mod)
{
	assert(filename&&mod);
	MYFILE* newfile=malloc(sizeof(MYFILE));
	if(newfile==NULL)
	{
		perror("mfopen->malloc::");
		exit(1);
	}
	memset(newfile, 0, sizeof(MYFILE));
	newfile->fileno=-1;
	newfile->cap=FILE_SIZE;
	if (strcmp(mod,"r")==0)
	{
		newfile->openmod=_READONLY;
		newfile->fileno = open(filename,O_RDONLY);
	}	
	else if (strcmp(mod,"w")==0)
	{
		newfile->openmod=_WRITEONLY;
		newfile->fileno = open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
	}
	else if (strcmp(mod,"a")==0)
	{
		newfile->openmod=_APPEND;
		newfile->fileno = open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);	
	}
	if(newfile->fileno==-1)
	{
		free(newfile);
		newfile=NULL;
		perror("mfopen->open::");
		exit(1);
	}
	return newfile;
}
int mfwrite(void* ptr, int num, MYFILE* stream)
{
	assert(ptr&&stream);
	int len = strlen(ptr);
	if (num>len)
	{
		num=len;
	}
	//int buffnum=0;
	char* pptr=ptr;
	while(num > stream->cap)
	{		
		memcpy(stream->outbuffer, pptr, stream->cap);
		stream->size=stream->cap;
		stream->flushmod=_FULL;
		mfflush(stream);
		num -= stream->cap;
		pptr += stream->cap;
		printf("%d %d\n",num,stream->cap);
	}
	if(num>0)
	{
		memcpy(stream->outbuffer, pptr, num);	
		stream->size=num;
		if(pptr[num-1] == '\n')
		{
			mfflush(stream);
		}
	}
	return 0;
}
int mfread(void* ptr, int num, MYFILE* stream)
{
	assert(ptr&&stream);
	read(stream->fileno,(void*)ptr,num);
	return 0;
}
void mfflush(MYFILE* stream)
{
	assert(stream);
	write(stream->fileno,stream->outbuffer,stream->size);
	//printf("%d %s %d\n",stream->fileno,stream->outbuffer,stream->size);
	memset(stream->outbuffer, 0, FILE_SIZE);
	stream->size=0;
}
void mfclose(MYFILE* stream)
{
	assert(stream);
	mfflush(stream);
	close(stream->fileno);
	free(stream);
	stream=NULL;
}
